package juc;

/**
 * @author fangkun
 * @create 2022-12-09-13:59
 */
public class ThreadLocalDemo2 {
    public static void main(String[] args) {
        House house = new House();

        new Thread(() ->{
            try {
                for (int i = 1; i <= 3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---"+house.threadLocal.get());
            } finally {
                //记得remove，如果不清理自定义的 ThreadLocal 变量，可能会影响后续业务逻辑和造成内存泄露等问题
                house.threadLocal.remove();
            }

        },"t1").start();

        new Thread(() ->{
            try {
                for (int i = 1; i <= 8; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---"+house.threadLocal.get());
            } finally {
                //记得remove，如果不清理自定义的 ThreadLocal 变量，可能会影响后续业务逻辑和造成内存泄露等问题
                house.threadLocal.remove();
            }

        },"t2").start();

        new Thread(() ->{
            try {
                for (int i = 1; i <= 12; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---"+house.threadLocal.get());
            } finally {
                //记得remove，如果不清理自定义的 ThreadLocal 变量，可能会影响后续业务逻辑和造成内存泄露等问题
                house.threadLocal.remove();
            }

        },"t3").start();

        System.out.println(Thread.currentThread().getName()+"\t"+"---"+house.threadLocal.get());
    }
}

class House{

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void saleHouse(){
        Integer value = threadLocal.get();
        value++;
        threadLocal.set(value);
    }
}